from support.utils.file.base import MediaFile
from PIL import Image
from PIL.ExifTags import TAGS
from support.ui.console import Log
        
class Picture(MediaFile):
    KB = 1024
    KEY_WIDTH = ['ImageWidth','ExifImageWidth']
    KEY_HEIGHT = ['ImageLength','ExifImageHeight']
    KEY_GPS = 'GPSInfo'
    KEY_DATE = 'DateTimeOriginal'
    WIDTH = 'Width'
    HEIGHT = 'Height'
    DATE = 'Date'
    LOAC = 'Local'
    HASH = 'Hash'

    def __calcDMS(self, value):
        return value if len(value)==1 else value[0]/value[1]

    def __transDMS(self, value):
        if('2' not in value.keys()):
            return ""
        latitudinal = self.__calcDMS(value[2][0]) + self.__calcDMS(value[2][1])/60.0 + self.__calcDMS(value[2][2]) /3600.0
        longitude = self.__calcDMS(value[4][0]) + self.__calcDMS(value[4][1])/60.0 + self.__calcDMS(value[4][2]) /3600.0

        return "{},{}".format(longitude if value[3].upper() == 'E' else -longitude, latitudinal if value[1].upper() == 'N' else -latitudinal)
            
    def __hasTag(self, filtermap, key):
        if(filtermap is None):
            return True
        for filter in filtermap:
            if(isinstance(filter, str) and key == filter):
                return True
            if(isinstance(filter, list) and key in filter):
                return True
        return False
        
    def __transKey(self, key):
        if(key == self.KEY_DATE):
            return self.DATE
        if(key == self.KEY_GPS):
            return self.LOAC
        if(key in self.KEY_HEIGHT):
            return self.HEIGHT
        if(key in self.KEY_WIDTH):
            return self.WIDTH
        return key
        
    def getMetaData(self, path, filtermap=None):
        metaData = {}
        metaData[self.HASH] = self.calHash(path)
        if(self.isVideo(path)):
            metaData[self.DATE] = self.getCreateDate(path)
        else:
            try:
                file = Image.open(path)
                info = file._getexif()
                if(info):
                    for (tag, value) in info.items():
                        key = TAGS.get(tag,tag)
                        if(self.__hasTag(filtermap, key)):
                            metaData[self.__transKey(key)] = self.__transDMS(value) if(key == self.KEY_GPS) else value
            except Exception as e:
                Log.e(__file__, type(e), str(e))
            finally:
                if(self.DATE not in  metaData.keys()):
                    metaData[self.DATE] = self.getCreateDate(path)
        return metaData

    def getData(self, meta, key, default=""):
        if(key not in meta.keys()):
            return default
        return meta[key]
